package lu.med.praxiswahl.wahlumed.client.zytologie;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

public class ProcessingMonitor extends JPanel implements PropertyChangeListener
{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JProgressBar progressBar;
    private Task task;
    private ZytologieTableModel model;

    public ProcessingMonitor(ZytologieTableModel model)
    {

	super(new BorderLayout());

	this.model = model;
	progressBar = new JProgressBar(0, 100);
	progressBar.setValue(0);
	progressBar.setStringPainted(true);

	JPanel panel = new JPanel();
	panel.add(progressBar);

	add(panel, BorderLayout.PAGE_START);
	setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    }

    class Task extends SwingWorker<Void, Void>
    {
	ZytologieTableModel model;

	public Task(ZytologieTableModel model)
	{
	    this.model = model;
	}

	@Override
	protected Void doInBackground() throws Exception
	{
            int progress = 0;
            //Initialize progress property.
            setProgress(0);
            while (progress < 100) {
                //Sleep for up to one second.
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ignore) {}
                //Make random progress.
                progress += 5;
                setProgress(Math.min(progress, 431));


	    }

	    return null;
	}

    }

    @Override
    public void propertyChange(PropertyChangeEvent evt)
    {
	if ("progress" == evt.getPropertyName())
	{
	    int progress = (Integer) evt.getNewValue();
	    progressBar.setValue(progress);
	}

    }

    /**
     * Create the GUI and show it. As with all GUI code, this must run on the
     * event-dispatching thread.
     */
    void createAndShowGUI()
    {
	// Create and set up the window.
	JFrame frame = new JFrame("ProgressBarDemo");

	// Create and set up the content pane.
	JComponent newContentPane = new ProcessingMonitor(this.model);
	newContentPane.setOpaque(true); // content panes must be opaque
	frame.setContentPane(newContentPane);

	setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
	// Instances of javax.swing.SwingWorker are not reusuable, so
	// we create new instances as needed.
	task = new Task(this.model);
	task.addPropertyChangeListener((ProcessingMonitor)newContentPane);
	task.execute();

	// Display the window.
	frame.pack();
	frame.setVisible(true);
    }

}
